// 使用内置的 fetch API（Node.js 18+）

const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkQXQiOjE3NTY4MzIzMDc5MjEsImVtYWlsIjoiOTI5MTQ0Mzg3QHFxLmNvbSIsImFjdGlvbiI6InRva2VuLWFwaSIsImFwaVZlcnNpb24iOiJ2MiIsImlhdCI6MTc1NjgzMjMwN30.SMO_QIYPvGgBFynqu2mynnU6BFfZLhs1x_ZNYSREg7c";
const WALLET = "FmsrseY6tzb58TDdoCoN25VNU1eTSHPwZCvpgaCmhjvV";
const headers = { Authorization: `Bearer ${API_KEY}` };

// 带重试的请求函数
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, {
        ...options,
        timeout: 15000, // 15秒超时
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return response;
    } catch (error) {
      console.log(`请求失败 (尝试 ${i + 1}/${maxRetries}):`, error.message);
      
      if (i === maxRetries - 1) {
        throw error;
      }
      
      // 等待后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
}

// 获取持仓
async function getTokens() {
  try {
    const url = `https://pro-api.solscan.io/v2.0/account/token-accounts?address=${WALLET}`;
    const res = await fetchWithRetry(url, { headers });
    const data = await res.json();
    
    if (!data.data) {
      throw new Error('API 返回数据格式错误');
    }
    
    return data.data.map(t => ({
      symbol: t.tokenSymbol,
      amount: t.uiAmount,
      price: t.priceUsdt,
      value: t.uiAmount * (t.priceUsdt || 0)
    }));
  } catch (error) {
    console.error('获取持仓失败:', error.message);
    return [];
  }
}

// 获取交易记录
async function getTransfers() {
  try {
    const url = `https://pro-api.solscan.io/v2.0/account/transfer?address=${WALLET}&limit=10&offset=0`;
    const res = await fetchWithRetry(url, { headers });
    const data = await res.json();
    
    if (!data.data) {
      throw new Error('API 返回数据格式错误');
    }
    
    return data.data;
  } catch (error) {
    console.error('获取交易记录失败:', error.message);
    return [];
  }
}

(async () => {
  const tokens = await getTokens();
  console.log("持仓:", tokens);

  const transfers = await getTransfers();
  console.log("最近交易:", transfers);
})();
